import { ref } from "vue";
import { useStore } from "vuex";

/**
 * 上传头像请求
 * @returns {{isLoading: Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>, handleAvatarChange: ((function(*, *): Promise<void>)|*)}}
 */
export function useAvatarUpload(PersonData) {
    const isLoading = ref(false); // 加载状态
    const store = useStore(); // 获取 Vuex Store 实例

    // const PersonData = ref({
    //     name: "罗小昔",
    //     showName: "false",
    //     gender: "male",
    //     avatar: "https://img.js.design/assets/img/671e031b4bb2e8ffc099b965.jpg#256cc8663039fbfe7f326b3d682f1c66",
    //     identity: 0,
    //     city: "杭州",
    //     birthdate: "2004-10-22",
    //     school: "浙江理工大学",
    //     graduateYear:"2026",
    //     vxNumber: "luoxiaoxixixi",
    //     intro: "这是我的个人简介，平平无奇的大学学生",
    //     resume: "罗小昔的个人简历.pdf",
    //     /*releaseNumber: "0",
    //     finishNumber: "0",
    //     creditScore: "100",*/
    // });

    // 处理头像上传
    const handleAvatarChange = async (event) => {
        const file = event.target.files[0];
        if (file) {
            const avatarFile = new FormData(); // 创建 FormData 实例
            avatarFile.append("file", file);

            isLoading.value = true; // 设置加载状态为 true
            try {
                // 调用 Vuex 中的 updateAvatar action
                const response = await store.dispatch("updateAvatar", avatarFile);
                if (response.success) {
                    PersonData.value.avatar = response.data; // 更新前端展示的头像
                    console.log(111,PersonData)
                    /*PersonData.avatar = "https://innoserve.oss-cn-hangzhou.aliyuncs.com/avatar/1e4741321cee473ca60879f6e096e382.png"*/
                } else {
                    alert(response.message || "头像上传失败");
                }
            } catch (error) {
                console.error("上传头像时出错:", error);
                alert("上传失败，请稍后重试");
            } finally {
                isLoading.value = false; // 重置加载状态
            }
        }
    };

    return {
        handleAvatarChange,
        isLoading,
    };
}
